package network.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTest {

	public Object copy(Object object) throws Exception{
		
		Class classType = object.getClass();
		System.out.println("Class:" + classType.getName());
		
		Object objectCopy = classType.getConstructor(
				new Class[]{}).newInstance(new Class[]{});
		
		Field[] fields = classType.getDeclaredFields();
		
		for(int i = 0; i < fields.length; i++){
			Field field = fields[i];
			
			String fieldName = field.getName();
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getMethodName = "get" + firstLetter + fieldName.substring(1);
			String setMethodName = "set" + firstLetter + fieldName.substring(1);
			
			Method getMethod = classType.getMethod(getMethodName, new Class[]{});
			Method setMethod = classType.getMethod(setMethodName, new Class[]{field.getType()});
			
			//调用原对象的get方法
			Object value = getMethod.invoke(object, new Object[]{});
			System.out.println(fieldName + ":" + value);
			
			//调用复制对象的set方法
			setMethod.invoke(objectCopy, new Object[]{value});
		}
		
		return objectCopy;
	}
	
	public static void main(String[] args) throws Exception{
		Customer customer = new Customer("Tom", 22);
		customer.setId(new Long(12345));
		
		Customer customerCpoy = (Customer) new ReflectTest().copy(customer);
		System.out.println("Copy information:" + customerCpoy.getName() + ","
				+ customerCpoy.getAge() + "," + customerCpoy.getId());
	}
}
